本系列對於基礎語法的最後一篇,想與大家分享使用PIVOT搭配聚合函數,可以將資料更靈活的做Excel的樞紐分析,以下透過簡單的例子教學。
SELECT *
FROM (
    SELECT <columns>
    FROM <table>
)
PIVOT (
    <aggregation_function>(<pivot_column>)
    FOR <pivot_column> IN (<value1>, <value2>, ..., <valueN>)
);
<table>: 要轉換的原始表<aggregation_function>: 聚合函數,如 SUM, AVG, COUNT等<pivot_column>: 需要被轉置的欄位<value1>, <value2>, ..., <valueN>: 這些值會成為新的欄位名稱以下為學生的 數學 與 英文 成績單,透過 PIVOT 來創造 By 科目 的成績表格
with scores as (
  select 'JACK' name, 45 score, 'Math' course from dual
  union all
  select 'AMY' name, 56 score, 'English' course  from dual
  union all
  select 'KAMY' name, 78 score, 'Math' course  from dual
  union all
  select 'Celine' name, 99 score, 'Math' course  from dual
  union all
  select 'Ryan' name, 100 score, 'English' course  from dual
)
select *
from scores
PIVOT(
    AVG(score)
    FOR course IN ('Math' as Math, 'English' as Eng)
)
;
| name | score | course | 
|---|---|---|
| JACK | 45 | Math | 
| AMY | 56 | English | 
| AMY | 78 | Math | 
| Celine | 99 | Math | 
| Celine | 99 | English | 
| JACK | 100 | English | 
| name | Math | Eng | 
|---|---|---|
| JACK | 45 | 100 | 
| AMY | 78 | 56 | 
| Celine | 99 | 99 |